'use strict';
var globalData_1 = require('../globalData');
exports.__esModule = true;

exports.formatTime = function (date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

var formatNumber = function (n) {
    var s = n.toString();
    return s[1] ? s : '0' + s;
};

exports.formatMsgTime = function (dateTime) {
    var Y = dateTime.getFullYear(); // 年

    var M = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1; // 月

    var D = dateTime.getDate() + 1 < 10 ? '0' + dateTime.getDate() : dateTime.getDate(); // 日
    // const h = (dateTime.getHours() + 1 < 10 ? '0' + (dateTime.getHours()) : dateTime.getHours()); // 时
    // const m = (dateTime.getMinutes() + 1 < 10 ? '0' + (dateTime.getMinutes()) : dateTime.getMinutes()); // 分

    var numberStr;
    numberStr = Y + '-' + M + '-' + D;
    return numberStr;
};

exports.formatDateTime = function (date) {
    var dateTime = new Date(date); // 将传进来的字符串或者毫秒转为标准时间

    var Y = dateTime.getFullYear(); // 年

    var M = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1; // 月

    var D = dateTime.getDate() + 1 < 10 ? '0' + dateTime.getDate() : dateTime.getDate(); // 日

    var h = dateTime.getHours() + 1 < 10 ? '0' + dateTime.getHours() : dateTime.getHours(); // 时

    var m = dateTime.getMinutes() + 1 < 10 ? '0' + dateTime.getMinutes() : dateTime.getMinutes(); // 分

    var numberStr;
    numberStr = Y + '-' + M + '-' + D + ' ' + h + ':' + m;
    return numberStr;
};

exports.formatYMTime = function (date) {
    var dateTime = new Date(date); // 将传进来的字符串或者毫秒转为标准时间

    var Y = dateTime.getFullYear(); // 年

    var M = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1; // 月
    // const D = (dateTime.getDate() + 1 < 10 ? '0' + (dateTime.getDate()) : dateTime.getDate()); // 日

    var numberStr;
    numberStr = Y + '-' + M;
    return numberStr;
};

exports.formatYMD = function (dateTime) {
    var Y = dateTime.getFullYear();
    var M = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1; // 月

    var D = dateTime.getDate() + 1 < 10 ? '0' + dateTime.getDate() : dateTime.getDate(); // 日

    return Y + '-' + M + '-' + D;
};
/*函数节流*/

var Throttle =
    /** @class */
    (function () {
        function Throttle() {
            var _this_1 = this;

            this.use = function (fn, delay) {
                if (delay === void 0) {
                    delay = 500;
                }

                var _this = _this_1;
                return (function () {
                    var args = [];

                    for (var _i = 0; _i < arguments.length; _i++) {
                        args[_i] = arguments[_i];
                    }

                    var backTime = new Date().getTime(); //第一次函数return即触发的时间

                    if (backTime - _this.enterTime > delay) {
                        fn.call(_this, args);
                        _this.enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
                    }
                })();
            };

            this.enterTime = 0; //触发的时间
        }

        return Throttle;
    })();

exports.Throttle = Throttle;
/*函数防抖*/

var Debounce = /** @class */ (function () {
    function Debounce() {
        var _this_1 = this;
        this.use = function (fn, delay) {
            if (delay === void 0) { delay = 500; }
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                if (_this_1.timer) {
                    clearTimeout(_this_1.timer);
                }
                if (_this_1.flag) {
                    fn.apply(_this_1, args);
                    _this_1.flag = false;
                }
                _this_1.timer = setTimeout(function () {
                    // console.log('执行123456')
                    _this_1.flag = true;
                }, delay);
            };
        };
        this.timer = undefined;
        this.flag = true;
    }
    return Debounce;
}());
exports.Debounce = Debounce;

exports.strlen = function (str) {
    var len = 0;

    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i); //单字节加1

        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 2;
        }
    }

    return len;
};
/**
 * 防抖
 * @param {function} fn 方法
 * @param {int} delay 延迟
 * @param {object} ctx 参数
 */
let timer;
function debounce(fn, delay, ctx) {
    if (delay === void 0) {
        delay = 0;
    }
    return function _() {
        clearTimeout(timer);
        var args = Array.prototype.slice.call(arguments);
        timer = setTimeout(function () {
            fn.apply(ctx, args);
        }, delay);
    };
}

/**
 * 链接判断是否是https,http还是小程序路径
 */

function LinkType(link) {
    console.log("LinkType==>", link);
    var pages = ['/pages', '/orderSub', '/homeSub', '/mine','/marketing_page'];
    var pageLink = pages.findIndex(function (item) {
        return link.indexOf(item);
    });

    if (/^(http|https):\/\/(.*)/.test(link)) {
        console.log("LinkType==>true", link);

		// #ifdef APP-PLUS
		plus.runtime.openURL(link);
		// #endif
		// #ifdef H5
		window.location.href = link
		// #endif
        // #ifdef MP-WEIXIN
        uni.navigateTo({
            url: '/components/webView/webView?link=' + link
        });
        // #endif
    } else if (pageLink != -1) {
        console.log("LinkType==>false", link);
        uni.navigateTo({
            url: link
        });
    }
}

// 获取字符串中的query
function getQueryData(url) {
    url = url.substring(url.indexOf("?") + 1);
    const str = url.split("&");
    const url_arr = {};
    for (let i = 0; i < str.length; i++) {
        const sttr = str[i].split("="); // sttr = [aaa,123]
        url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
    }
    return url_arr;
}
exports.getQueryData = getQueryData;

// 防抖跳转登录页
function toLogin(tip){
	uni.hideLoading()
	debounce(()=>{
		console.log('aaa,已经是登录页面了1')
		uni.removeStorageSync('unionId')
		uni.removeStorageSync('openId')
		uni.removeStorageSync('memberType')
		uni.removeStorageSync('token')
		//#ifdef H5
        if(isxmgjMix()){
            if(getQueryData(window.location.href).token){
                window.location.href = window.location.href
            }else{
                window.location.href = window.location.href + `&token=${uni.getStorageSync('xmgjToken')}`
            }
            return
        }
		
		if(isZshAppInH5()){
		    if(getQueryData(window.location.href).token){
		        window.location.href = window.location.href
		    }else{
		        window.location.href = window.location.href + `&data=${uni.getStorageSync('zsjToken')}`
		    }
		    return
		} else if (isCdgj()) {
            logBackIn({
                sellerTokenKey: 'cdgjToken',
                urlTokenKey: 'data'
            })
            return
        }
		//#endif
	    uni.showModal({
		    title: '提示',
		    content: tip || "登录过期，请重新授权",
		    showCancel:false,
		    confirmText:'重新登录',
		    success: function () {
				// #ifdef H5
				let gunDetailUrl = window.location.href
				uni.setStorageSync('gunDetailUrl',gunDetailUrl)
				// alert(gunDetailUrl) cyc
				// #endif
			    let pages = getCurrentPages()

                const loginUrl = "packagePersonal/pages/login/login"
			    if (!(getCurrentPages()[pages.length - 1].route == loginUrl)) {
				    uni.navigateTo({
					    url: `/${loginUrl}`
				    });
			    } 
		    }
	    })
	}, 1000,false)()
}

/**
 * 重新登录
 * @param {*} params 
 * sellerTokenKey: 存储的tokenkey
 * urlTokenKey: 链接中携带的tokenkey
 */
function logBackIn(options) {
    const { sellerTokenKey, urlTokenKey } = options

    const href = window.location.href
    const cacheToken = uni.getStorageSync(sellerTokenKey)
    if(getQueryData(href)[urlTokenKey]){
        // 链接中有token，直接跳转
        window.location.href = href
    } else if (cacheToken) {
        // 缓存中有token，直接跳转
        const str = href.includes('?') ? '&' : '?'
        window.location.href = `${href}${str}${urlTokenKey}=${cacheToken}`
    }
}
exports.LinkType = LinkType;
exports.toLogin = toLogin;

/**
 * wx.showLoading
 */
var loadingDebounce = new Debounce();
function showLoading(object) {
    object = object || {};
    object.title = object.title || '加载中';
    object.mask = object.mask || true;
    // 防抖
    loadingDebounce.use(wx.showLoading, 800)(object);
}
exports.showLoading = showLoading;
/**
 * wx.hideLoading
 */
var hideLoadingDebounce = new Debounce();
function hideLoading() {
    // 防抖
    hideLoadingDebounce.use(wx.hideLoading, 800)();
}
exports.hideLoading = hideLoading;
/**
 * 设置营销获客请求服务奔溃状态
 */
var setCurrentPagemarketingSwitchDebounce = new Debounce();
function setCurrentPagemarketingSwitch() {

    setCurrentPagemarketingSwitchDebounce.use(function () {
         var marketingSwitch = wx.getStorageSync('marketingSwitch');
                var tokenMemberType = wx.getStorageSync('memberType');
                var pages = getCurrentPages();
                var currentPage = pages[pages.length - 1];
                console.log(marketingSwitch,tokenMemberType,'这是状态哈哈哈哈')
                
                try{
                    // currentPage.setData({
                    //     marketingSwitch: 
                    // });
                    console.log('走到了这里哈哈哈',currentPage)
                    // #ifdef MP-WEIXIN
                    currentPage.$vm.setData({
                        marketingSwitch:(!marketingSwitch && tokenMemberType != 0)
                    })
                    // #endif
                    
                    // #ifndef H5
                        currentPage.marketingSwitch=(!marketingSwitch && tokenMemberType != 0)
                    // #endif
                }catch(e){
                    //TODO handle the exception
                    currentPage.marketingSwitch = (!marketingSwitch && tokenMemberType != 0)
                }
    }, 500)();
}
exports.setCurrentPagemarketingSwitch = setCurrentPagemarketingSwitch;


// 判断是否巨湾
function isJw(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'jw' 
	// #endif
	return false
}

exports.isJw = isJw

// 判断是否能银链h5
function isnylH5(){
	// #ifdef H5
		// return globalData_1.default.sellerNo == 'nyl' 
		return globalData_1.default.sellerNo == 'dstadmin'
	// #endif
    return false
}

exports.isnylH5 = isnylH5


// 判断是否创烨-光烨科技
function iscy(){
    return globalData_1.default.sellerNo == 'cy' 
}
exports.iscy = iscy

// 判断是否长治
function isChangzhi(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'changzhi' 
	// #endif
    return false
}

exports.isChangzhi = isChangzhi


// 判断是否厦门公交
function isxmgjMix(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'xmgj' 
	// #endif
	return false
}

exports.isxmgjMix = isxmgjMix

// 判断是否宣城
function isSellerXc(){
    return globalData_1.default.sellerNo == 'xc' 
}
exports.isSellerXc = isSellerXc


// 判断是否招商局内嵌H5
function isZsjInH5(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'zsj'
	// #endif
	return false
}
exports.isZsjInH5 = isZsjInH5

// 判断是否招商局小程序内嵌H5
function isZsjMiniInH5(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'zsj' && uni.getStorageSync('clientType') == 'mini'
	// #endif
	return false
}
exports.isZsjMiniInH5 = isZsjMiniInH5

// 判断是否招商局APP内嵌H5
function isZshAppInH5(){
	// #ifdef H5
		return globalData_1.default.sellerNo == 'zsj' && uni.getStorageSync('clientType') == 'app'
	// #endif
	return false
}
exports.isZshAppInH5 = isZshAppInH5



// 判断是否中核
function isCsht(){
	return globalData_1.default.sellerNo == 'csht'
}
exports.isCsht = isCsht


// 判断是否交发e充电
function isLgxny(){
	return globalData_1.default.sellerNo == 'lgxny'
}
exports.isLgxny = isLgxny

// 判断是否成都公交
function isCdgj(){
	return globalData_1.default.sellerNo == 'cdgj'
}
exports.isCdgj = isCdgj


/**
 * 加密特殊字符串符号处理
 * @param {*} val 
 * @returns 
 */
function decodeCharacter(val) {
    const str = val
    .replace(/%40/gi, '@')
    .replace(/%3A/gi, ':')
    .replace(/%24/g, '$')
    .replace(/%2C/gi, ',')
    .replace(/%20/g, '+')
    .replace(/%5B/gi, '[')
    .replace(/%5D/gi, ']')
    return decodeURIComponent(str)
}
exports.decodeCharacter = decodeCharacter

// 判断是否驿满充电
function isCqym(){
	return globalData_1.default.sellerNo == 'cqym'
}
exports.isCqym = isCqym


// 判断招小服
function isTjhz(){
	return globalData_1.default.sellerNo == 'tjhz'
}
exports.isTjhz = isTjhz

// 判断畅桐易充
function isChangtong(){
	return globalData_1.default.sellerNo == 'changtong'
}
exports.isChangtong = isChangtong

// 是否为川逸充app内嵌h5
function isCYCAPPInH5(){
    // #ifdef H5
    const sellerNoList = ['test_dev']
    return sellerNoList.includes(globalData_1.default.sellerNo)
    // #endif
    return false
}
exports.isCYCAPPInH5 = isCYCAPPInH5

// 判断是否是AI快充
function isAIKC(){
	return globalData_1.default.sellerNo == 'AIKC'
}
exports.isAIKC = isAIKC

// 设置当前页面的url参数 将格式{a:1,b:2} 转换成 '?a=1&b=2'
function setOptionsToUrlQuery (options) {
    var query = options || {};
    var str = [];
    var queryStr = '';
    for (var p in query) {
        if (query[p]) {
            str.push(p + "=" + query[p]);
        }
    }
    queryStr = str.join("&");
    if (queryStr) {
        return '?' + queryStr;
    }
    return queryStr;
}
exports.setOptionsToUrlQuery = setOptionsToUrlQuery;

// 获取URL 中的参数 将格式'?a=1&b=2' 转换成{a:1,b:2}
function getUrlDataToObj (url) {
    const match = url.match(/[^?]+$/); // 截取最后一个问号
    url = match[0];
    const str = url.split("&");
    const url_arr = {};
    for (let i = 0; i < str.length; i++) {
        const sttr = str[i].split("="); // sttr = [aaa,123]
        url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
    }
    return url_arr;
}
exports.getUrlDataToObj = getUrlDataToObj;


// 设置新的tag对象， 如 {a:1,b:2} => {tag_a:1,tag_b:2}
const setNewTagObject = (obj, tagStr = '') => {
    let tempObj = {}

    if (obj && Object.keys(obj).length > 0) {
        for(let keyName in obj) {
            const newKeyName = tagStr + keyName
            tempObj[newKeyName] = obj[keyName]
        }
    }

    return tempObj
}
exports.setNewTagObject = setNewTagObject;

// 获取tag对象， 如 {tag_a:1,tag_b:2} => {a:1,b:2}
const getNewTagObject = (obj, tagStr = '') => {
    let tempObj = {}

    if (obj && Object.keys(obj).length > 0) {
        for(let keyName in obj) {
            if (keyName.includes(tagStr)) {
                const newKeyName = keyName.replace(tagStr, '')
                tempObj[newKeyName] = obj[keyName]
            }
        }
    }

    return tempObj
}
exports.getNewTagObject = getNewTagObject;